package org.yelongframework.excel.poi.workbook;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.yelongframework.commons.io.IOUtil;
import org.yelongframework.excel.workbook.ExcelWorkbook;
import org.yelongframework.lang.Nullable;
import org.yelongframework.poi.DefaultPOIExcelSupport;
import org.yelongframework.poi.POIExcelSupport;

/**
 * 默认实现
 * 
 * @since 1.0.0
 */
public class DefaultPOIExcelWorkbookFactory implements POIExcelWorkbookFactory {

	/** 默认Excel支持 */
	public static final POIExcelSupport DEFAULT_POI_EXCEL_SUPPORT = new DefaultPOIExcelSupport();

	/** Excel支持 */
	@Nullable
	private POIExcelSupport poiExcelSupport;

	// ==================================================构造器==================================================

	public DefaultPOIExcelWorkbookFactory() {
	}

	/**
	 * @param poiExcelSupport Excel支持
	 */
	public DefaultPOIExcelWorkbookFactory(POIExcelSupport poiExcelSupport) {
		this.poiExcelSupport = poiExcelSupport;
	}

	// ==================================================文件流==================================================

	@Override
	public ExcelWorkbook create(InputStream inputStream) throws IOException {
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(IOUtils.toByteArray(inputStream));
		IOUtil.closeQuietly(inputStream);
		Workbook workbook;
		try {
			workbook = new XSSFWorkbook(byteArrayInputStream);
		} catch (Exception e) {
			byteArrayInputStream.reset();
			workbook = new HSSFWorkbook(new POIFSFileSystem(byteArrayInputStream));
		}
		return create(workbook);
	}

	// ==================================================工作薄==================================================

	@Override
	public ExcelWorkbook create(Object workbook) {
		if (!(workbook instanceof Workbook)) {
			throw new IllegalArgumentException("workbook必须是【" + Workbook.class + "】的实例");
		}
		return new DefaultPOIExcelWorkbook((Workbook) workbook,
				poiExcelSupport != null ? poiExcelSupport : DEFAULT_POI_EXCEL_SUPPORT);
	}

	// ==================================================POI工作薄支持==================================================

	@Override
	public POIExcelSupport getPOIExcelSupport() {
		return poiExcelSupport;
	}

	@Override
	public void setPOIExcelSupport(POIExcelSupport poiExcelSupport) {
		this.poiExcelSupport = poiExcelSupport;
	}

}
